//https://leetcode.cn/problems/coin-change/description/?envType=daily-question&envId=2024-03-24

class Solution {
public:
    //优化后的代码
    int coinChange(vector<int>& coins, int amount) {
        int n = coins.size();
        vector<int> dp(amount + 1, -1);
        dp[0] = 0;
        for (int i = 1; i <= n; i++) 
        {
            for (int j = coins[i - 1]; j <= amount; j++) 
            {
                if (dp[j - coins[i - 1]] != -1) 
                {
                    if (dp[j] == -1) 
                    {
                        dp[j] = dp[j - coins[i - 1]] + 1;
                    } 
                    else 
                    {
                        dp[j] = min(dp[j], dp[j - coins[i - 1]] + 1);
                    }
                }
            }
        }
        return dp[amount];
    }
    //源代码
    /*int coinChange(vector<int>& coins, int amount) {
        int n = coins.size();
        vector<vector<int>> dp(n + 1, vector<int>(amount + 1));
        for (int i = 1; i <= amount; i++) dp[0][i] = -1;
        for (int i = 1; i <= n; i++) 
        {
            for (int j = 0; j <= amount; j++) 
            {
                dp[i][j] = dp[i - 1][j];
                if (j >= coins[i - 1] && dp[i][j - coins[i - 1]] != -1) 
                {
                    if (dp[i][j] == -1) 
                    {
                        dp[i][j] = dp[i][j - coins[i - 1]] + 1;
                    } 
                    else 
                    {
                        dp[i][j] = min(dp[i][j], dp[i][j - coins[i - 1]] + 1);
                    }
                }
            }
        }
        return dp[n][amount];
    }*/
};
